/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vng.zing.survey.data;

import static com.vng.zing.survey.data.Base.serialize;
import com.vng.zing.survey.thrift.model.SurveyItem;
import com.vng.zing.survey.thrift.model.Error;
import com.vng.zing.survey.thrift.model.SurveyItemResult;
import java.io.IOException;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import kyotocabinet.DB;

/**
 *
 * @author kienpd
 */
public class SurveyData extends Base {

    private static final Lock createLock_ = new ReentrantLock();
    private static SurveyData _instance = null;
    private static int buffer_size_profilevip = 0;
    private DB db;

    public SurveyData() {
        db = new DB();
        if (!db.open("database/survey.kch", DB.OWRITER | DB.OCREATE)) {
            System.err.println("open error: " + db.error());
        }

    }

    public static SurveyData getInstance() {
        if (_instance == null) {
            createLock_.lock();
            try {
                if (_instance == null) {
                    _instance = new SurveyData();
                }
            } finally {
                createLock_.unlock();
            }
        }
        return _instance;
    }

    public Error setSurvey(int idSurvey, SurveyItem surveyItem) {
        try {
            byte[] key = serialize(idSurvey);
            byte[] value = serialize(surveyItem);
            if (!db.set(key, value)) {
                return Error.ERR_SYSTEM;


            }
            return Error.SUCCESS;
        } catch (IOException ex) {
            Logger.getLogger(SurveyData.class.getName()).log(Level.SEVERE, null, ex);
        }
        return Error.ERR_SYSTEM;
    }

    public SurveyItem getSurvey(int idSurvey) {

        try {
            byte[] key = serialize(idSurvey);
            byte[] value = db.get(key);
            if (value == null) {

                return null;
            }
            SurveyItem surveyItem = new SurveyItem();
            surveyItem = (SurveyItem) deserialize(value);
            return surveyItem;
        } catch (Exception ex) {
            //Logger.getLogger(SurveyData.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;

    }
    public Error removeSurvey(int idSurvey){
        try {
            byte[] key = serialize(idSurvey);
            if(!db.remove(key)){
             return Error.IDSURVEY_NO_EXITS;
            }
            return Error.SUCCESS;
        } catch (Exception ex) {
            Logger.getLogger(SurveyData.class.getName()).log(Level.SEVERE, null, ex);
        }
        return Error.ERR_SYSTEM;
    }
}
